const http = require("http");
const fs = require("fs");
const path = require("path");
const serve = http.createServer();
var dirname = "static"
var name = "xxx";
serve.on("request", (req, res) => {
    var filepath = path.join(__dirname, dirname, req.url)
    console.log(req.url);
    if (req.url == "/") {
        res.setHeader('Content-Type', "text/html;charset=utf-8");
        filepath = path.join(__dirname, dirname, "index.html")
        var data2 = fs.readFileSync(filepath, 'utf-8')
        var newhtml = data2.toString().replace('xxx', name).trim()
        res.end(newhtml);
    }
    if (req.url == "/favicon.ico") {
        filepath = path.join(__dirname, dirname, "img", "120px-八奈見杏菜.jpg")
    }
    if (req.url.indexOf('name') != -1 && req.method == "GET") {
        let url = new URL(req.url, "http://localhost:3000/");
        console.log(url.searchParams.get("name"));
        if (url.searchParams.get("name")) {
            name = url.searchParams.get("name")
            //重定向到首页
            res.statusCode = 302;
            res.setHeader('location', '/')
            res.end();
        }
        else {
            res.end('你提交的内容为空')
        }
    }
  
    fs.readFile(filepath,(err,data)=>{ 
        if(err){
            res.end(err);
        }else{
            res.end(data);
        }
    });
});

serve.listen("3000", () => {
    console.log("服务启动成功,请访问http://10.10.49.42:3000/,或http://127.0.0.1:3000/,或http://localhost:3000/");
})